//
//  LoginView.m
//  Trading365
//
//  Created by yifei tong on 12-1-6.
//  Copyright (c) 2012年 dhc. All rights reserved.
//

#import "LoginView.h"
#import "TaskManager.h"
#import "XmlRpc.h"
#import "myToast.h"
#import "AppDelegate.h"
#import "DHCUtil.h"
#import "RootMissionToDo.h"
#import "RootMore.h"
#import "HttpServerURL.h"
#import "InfoType.h"

@implementation LoginView
@synthesize m_textFieldCompanyID;
@synthesize username;
@synthesize password;
@synthesize ver_server;

@synthesize m_tableView;
@synthesize m_ConfirmBut;
@synthesize m_CancelBut;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    //    [username release];
    //    [password release];
    //    [m_textFieldCompanyID release];
    //    [super dealloc];
}
#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [UIView setAnimationDuration:15];
    m_rect = self.view.frame;
    loginSuccess = NO;
    //触摸 textfield
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidBeginEditing:) name:UITextFieldTextDidBeginEditingNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidEndEditing:) name:UITextFieldTextDidEndEditingNotification object:nil];
    
    [self.view setBackgroundColor:BACKGROUND_COLOR];
    
    UIImage *barMergeButImageNormal = [UIImage imageNamed:PIC_MORE_CONFIRM_NORMAL];
    UIImage *barMergeButImagePress = [UIImage imageNamed:PIC_MORE_CONFIRM_PRESS];
    [m_ConfirmBut setBackgroundImage:barMergeButImageNormal forState:UIControlStateNormal];
    [m_ConfirmBut setBackgroundImage:barMergeButImagePress forState:UIControlStateHighlighted];
    
    barMergeButImageNormal = [UIImage imageNamed:PIC_MORE_CANCEL_NORMAL];
    barMergeButImagePress = [UIImage imageNamed:PIC_MORE_CANCEL_PRESS];
    [m_CancelBut setBackgroundImage:barMergeButImageNormal forState:UIControlStateNormal];
    [m_CancelBut setBackgroundImage:barMergeButImagePress forState:UIControlStateHighlighted];
    
    if (flagLoginType == INFO_TYPE_LOGIN_BLANK){
        return;
    }
    //读取系统Session    
//    [self reloadLoginData];
    
    [[Session share] printMember];
    
}

- (void)viewDidAppear:(BOOL)animated
{

    if (flagLoginType == INFO_TYPE_LOGIN_MANU){
        //读取系统Session    
        [self reloadLoginData];
    }    
}

-(void)viewWillAppear:(BOOL)animated
{
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


-(void)reloadLoginData
{
    NSString *filePath = [[[NSString alloc] initWithString: [DHCUtil dataFilePath]] autorelease];
    //    NSLog(@"filePath=%@",filePath);
    if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        NSMutableDictionary *userinfo = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
        NSString *companyCode=[userinfo objectForKey:Key_SaveLogin_CompanyCode];
        NSString *userName=[userinfo objectForKey:Key_SaveLogin_UserName];
        NSString *passWord=[userinfo objectForKey:Key_SaveLogin_PassWord];
        
        if (companyCode == nil || userName == nil || passWord == nil){
            //        if ( userName == nil || passWord == nil){
            flagLoginType=INFO_TYPE_LOGIN_BLANK;
            [[Session share] setLoginFlag:NO];
            self.view.hidden = NO;
        }
        else{
            [m_textFieldCompanyID setText:companyCode];
            [username setText:userName];
            [password setText:passWord];

            self.view.hidden = YES;
            [self OnLogin];
        }
        
        [userinfo release];
    }
}



#pragma mark - 
#pragma mark - my function
-(void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    if ([[Session share] isLogined] == NO ) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"您未登录" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        
    }
}

-(void) OnPreExcute
{
    
}

-(void) DoInBackground
{
    [self OnLogin];
    
}

-(void) OnLogin
{
    
    loginSuccess = NO;
    NSString *UserName =  [[NSString alloc] initWithString: self.username.text];
    NSString *PassWord =  [[NSString alloc] initWithString: self.password.text]; 
    NSString *Origin =  [[UIDevice currentDevice] model];//@"iphone";
    NSString *CompanyCode=[[NSString alloc] initWithString: self.m_textFieldCompanyID.text];
    
    //首先从portal获取企业码对应的url
    XmlRpc *xmlrpc = [[XmlRpc alloc] init];
    NSString *ret_url=@"" ;  
    //内网测试，注释下面一行即可
    ret_url = [xmlrpc GetSubURLFromPortal:CompanyCode];
    
    if ([ret_url length] > 0){
        NSLog(@"GetSubURLFromPortal=%@",ret_url);  
        
        if ([ret_url isEqualToString:@"企业码不存在!"]){
            
            if (flagLoginType == INFO_TYPE_LOGIN_MANU)
                [myToast showWithText:@"企业码不存在!"];
            
            [CompanyCode release];
            [UserName release];
            [PassWord release];
            //            [xmlrpc release];
            [self.view setHidden:NO];
            flagLoginType = INFO_TYPE_LOGIN_MANU;
  
            return;
        }
        
        [[HttpServerURL GetInstance] SetAllServerURL:ret_url];
    }

    [[HttpServerURL GetInstance] PrintAllServerURL];
    
    // init the params
    //    XmlRpc *xmlrpc = [[XmlRpc alloc] init];
    NSMutableDictionary *userinfo_tmp=nil ;  
    userinfo_tmp = [xmlrpc Member_Login:UserName PassWord:PassWord Origin:Origin];
    if ([userinfo_tmp count] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"登录失败" message:@"用户名或密码不正确" delegate:nil cancelButtonTitle:@"重试" otherButtonTitles: nil , nil];
        [alert show];
        [alert release];
        
        [UserName release];
        [PassWord release];
        [xmlrpc release];
       
        [self.view setHidden:NO];
        return;
    }
    
    if (flagLoginType == INFO_TYPE_LOGIN_MANU)
    {
        [myToast showWithText:@"登陆成功"];
    }
    
    NSString *filePath = [[[NSString alloc] initWithString: [DHCUtil dataFilePath]] autorelease];
    
    NSMutableDictionary *userinfo = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    if (userinfo == nil)
        userinfo = [[NSMutableDictionary alloc] initWithCapacity:0];
    
    //    NSMutableDictionary *userinfo=[[NSMutableDictionary alloc] initWithCapacity:5];
    
    [userinfo setValue:[userinfo_tmp objectForKey:Key_SaveLogin_UserID] forKey:Key_SaveLogin_UserID];
    [userinfo setValue:self.m_textFieldCompanyID.text forKey:Key_SaveLogin_CompanyCode];
    [userinfo setValue:self.username.text forKey:Key_SaveLogin_UserName];
    [userinfo setValue:self.password.text forKey:Key_SaveLogin_PassWord];
    [userinfo setValue:[userinfo_tmp objectForKey:Key_SaveLogin_NickName] forKey:Key_SaveLogin_NickName];
    [userinfo setValue:[userinfo_tmp objectForKey:Key_SaveLogin_RoleID] forKey:Key_SaveLogin_RoleID];
    [userinfo setValue:[userinfo_tmp objectForKey:Key_SaveLogin_PosiID] forKey:Key_SaveLogin_PosiID];
    [userinfo setValue:[userinfo_tmp objectForKey:Key_SaveLogin_PosiName] forKey:Key_SaveLogin_PosiName];
    
    //是否为经理权限
    NSString *perm=[userinfo_tmp objectForKey:Key_SaveLogin_Permission];
    [userinfo setValue:perm forKey:Key_SaveLogin_Permission];
    
    if ([perm isEqualToString:@"0"]){
        [[Session share] setPermission:NO];
    }else{
        [[Session share] setPermission:YES];
    }
    
    [[Session share] setMember:userinfo];
    [[Session share] setCompanyCode:CompanyCode];
    [[Session share] setLoginFlag:YES];
    
    //是否启用商机
    NSString * chance=[userinfo_tmp objectForKey:Key_SaveLogin_isChance];
    if ([chance isEqualToString:@"1"]){
        [[Session share] setChance:YES];
    }else{
        [[Session share] setChance:NO];        
    }
    [userinfo setValue:chance forKey:Key_SaveLogin_isChance];
    
    //最新版本
    self.ver_server=[userinfo_tmp objectForKey:Key_Settings_Version];
    
    //最新未读消息数量
    NSString *msgcount=[userinfo_tmp objectForKey:Key_Message_Count1];
    [[Session share] setMsgCount1:[msgcount intValue]];
    msgcount=[userinfo_tmp objectForKey:Key_Message_Count2];
    [[Session share] setMsgCount2:[msgcount intValue]];
    msgcount=[userinfo_tmp objectForKey:Key_Message_Count3];
    [[Session share] setMsgCount3:[msgcount intValue]];
    msgcount=[userinfo_tmp objectForKey:Key_Message_Count4];
    [[Session share] setMsgCount4:[msgcount intValue]];
    msgcount=[userinfo_tmp objectForKey:Key_Message_Count5];
    [[Session share] setMsgCount5:[msgcount intValue]];
    
    //获取发件人邮箱
    NSString *mailaddress=[userinfo_tmp objectForKey:Key_Mail_Address];
    [[Session share] setMailAddress:mailaddress];
    
    
    [userinfo writeToFile:[DHCUtil dataFilePath] atomically:YES]; 
    
    loginSuccess = YES;
    [[Session share] printMember];
    
    [CompanyCode release];
    [userinfo release];
    [UserName release];
    [PassWord release];
    [xmlrpc release];
    
    [self LoginSuccess];
}
-(void) LoadBackGroundData
{
    
}

-(void) OnPostExcute
{
    [spinner stopAnimating];
    //    [UIView setAnimationDuration:3];
    [UIView setAnimationDelay:5];
    [self.navigationController popViewControllerAnimated:YES];
    [UIView commitAnimations];
}

-(IBAction)LogoutBtn:(id)sender
{
    //    NSLog(@"userid=%@",[[Session share] getMemberID]);
    [[Session share] setLoginFlag:NO];
    exit(0);
    
}

-(IBAction)LoginBtn:(id)sender
{
    [username resignFirstResponder];
    [password resignFirstResponder];
    
    // get the user input
    NSString *CompanyCode=[[NSString alloc] initWithString: self.m_textFieldCompanyID.text];
    NSString *UserName =  [[NSString alloc] initWithString: self.username.text];
    NSString *PassWord =  [[NSString alloc] initWithString: self.password.text]; 
    
    // Check the input elements
    if ([CompanyCode isEqualToString:@""] || [UserName isEqualToString:@""] || [PassWord isEqualToString:@""])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"输入项错误" message:@"输入项不能为空！" delegate:nil cancelButtonTitle:@"重试" otherButtonTitles: nil , nil];
        [alert show];
        [alert release];
        
        [CompanyCode release];
        [UserName release];
        [PassWord release];
        return;
    }
    
    flagLoginType=INFO_TYPE_LOGIN_MANU;
    [[[TaskManager Share] GetTaskByType:LOGIN Delegate:self] Excute];  
    
     spinner = [[TKLoadingAnimationView alloc] initWithFrame:CGRectMake(140, 255, 30, 30) 
														tkLoadingAnimationViewStyle:TKLoadingAnimationViewStyleCarton];
	
	[self.view addSubview:spinner];
	[spinner startAnimating];
	[spinner release];
    [CompanyCode release];
    [UserName release];
    [PassWord release];
    
}

-(void)saveLoginData:(NSMutableDictionary *)dict
{
    // save data
    [dict writeToFile:[DHCUtil dataFilePath] atomically:YES];    
}
-(void)LoginAutoShow
{
    NSString *filePath = [[[NSString alloc] initWithString: [DHCUtil dataFilePath]] autorelease];
    
    //NSLog(@"%@",filePath);
    if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        NSDictionary *muDict = [[NSDictionary alloc] initWithContentsOfFile:filePath];
        
        self.username.text = [muDict valueForKey:Key_SaveLogin_UserName];
        self.password.text = [muDict valueForKey:Key_SaveLogin_PassWord];
        [muDict release];
    }
}

-(void) LoginSuccess
{
    //系统启动之初，检测新版本
    [self checkUpdateFromServer];
    
//    if (loginSuccess == NO){
//        sleep(10);
//    }
    
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    //[[[[[self tabBarController] viewControllers] objectAtIndex: indexICareAbout] tabBarItem] setBadgeValue:badgeValue];
    
    RootMissionToDo *missionTodo=[appDelegate getMissionTodoViewCtl];
    [missionTodo refreshData];
    [missionTodo.table reloadData];

    RootMore *more=[appDelegate getMoreViewCtl];
    [more refreshData];
    [more.table reloadData];

    //    [appDelegate.window addSubview:[appDelegate.viewController view]];
    //登陆成功后，移除自己
    [self.view removeFromSuperview];
}

//全局变量初始化
-(void)initTradingApp
{
    //读取系统session
    //    [[Session share] loadLoginData];
    
}
-(IBAction)dismissKeyBoard:(id)sender
{  
    [username resignFirstResponder]; 
    [password resignFirstResponder]; 
    [m_textFieldCompanyID resignFirstResponder]; 
} 
//******************************************************
// Method:     textFieldDidBeginEditing
// Access:     public 
// Returns:    BOOL
// Parameter:  textField
// Note:	   
// Author      muzongcun  2012/03/12 create
//*******************************************************
- (IBAction)textFieldDidBeginEditing:(UITextField *)textField
{
	//[UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
	//[UIView setAnimationDuration:0.30f];  
	self.m_tableView.frame = CGRectMake(0.0, -145.0, 320.0, 460);
	[UIView commitAnimations];
}

- (IBAction)textFieldDidEndEditing:(UITextField *)textField
{
	[UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
	[UIView setAnimationDuration:0.30f];  
	self.m_tableView.frame = m_rect;
	[UIView commitAnimations];
}

-(void) setFlagLoginType:(int)flag
{
    flagLoginType = flag;
    
}

-(void) checkUpdateFromServer
{
    NSString *filePath = [[[NSString alloc] initWithString: [DHCUtil dataFilePath]] autorelease];
    NSMutableDictionary *settings_info = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    
    NSString *curVer=[[NSString alloc] initWithFormat:@"%@",[settings_info objectForKey:Key_Settings_Version]]; 
    
//    NSLog(@"curVer=%@;",curVer);
    if ([curVer isEqualToString:@"(null)"])
        curVer=@"1.0";

    NSString *curDate=[[NSString alloc] initWithFormat:@"%@",[settings_info objectForKey:Key_Settings_UpdateDate]];
    
    [settings_info release];
    
    if (![ver_server isEqualToString:curVer]){
        NSString *nowDate=[DHCUtil getCurrentDate];
        
        //注：每天只需要更新一次
        if (![nowDate isEqualToString:curDate]){
            [self setSettingsFileData:Key_Settings_UpdateDate Value:nowDate];
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"有新版本，请更新。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles: @"确定" , nil];
            [alert show];
            [alert release];           
        }
    }
    
    [curVer release];   
    [curDate release];
    
}


-(void) setSettingsFileData:(NSString *)key Value:(NSString *)value
{
    NSString *filePath = [[[NSString alloc] initWithString: [DHCUtil dataFilePath]] autorelease];
    NSMutableDictionary *settingInfo = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
    
    if (settingInfo == nil)
        settingInfo = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
    
    [settingInfo setValue:value forKey:key];
    //    NSLog(@"setSettingsFileData:settingInfo=%@",settingInfo);
    
    [settingInfo writeToFile:filePath atomically:YES];  
    //[settingInfo release];
}

//定义的委托，buttonindex就是按下的按钮的index值
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //到 app store更新
    if (buttonIndex == 1){
        NSLog(@"go to app store,%i",buttonIndex);
        [self setSettingsFileData:Key_Settings_Version Value:self.ver_server];
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:APP_STORE_URL]];
    }
}

@end
